#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
订单记录表格组件 - 重构版本

重构说明：
- 移除了所有客户端文件监控功能
- 所有数据现在完全来自服务端
- 通过WebSocket接收实时数据更新
- 简化了OrderRow类，只负责显示数据
- 添加了数据刷新机制
"""

from PyQt6.QtWidgets import (QWidget, QVBoxLayout, QHBoxLayout, QLabel, 
                             QPushButton, QComboBox, QTableWidget, QTableWidgetItem,
                             QCheckBox, QHeaderView, QFrame, QMessageBox, QDialog,
                             QLineEdit, QTextEdit, QGridLayout, QDateEdit)
from PyQt6.QtCore import Qt, pyqtSignal, QTimer, QUrl
from PyQt6.QtGui import QFont, QDesktopServices
import os
import threading
import time
import re
from typing import Dict, List, Optional




class OrderRow:
    """订单行类，负责显示单个订单的状态信息"""
    
    def __init__(self, order_data: dict, table_widget):
        self.order_data = order_data
        self.table_widget = table_widget
        self.row_index = -1
        
        # 从订单数据中提取信息
        self.number = order_data.get('number', '')
        self.customer = order_data.get('customer', '')
        self.order_path = order_data.get('path', '')
        self.status = order_data.get('status', '未知')
        
        # 状态文件夹信息（从服务端数据获取）
        self.status_folders = set()
        self.files_count = {}  # 记录各状态文件夹的文件数量
        
        # 初始化状态信息
        self._update_status_from_data(order_data)
        
    def update_data(self, order_data: dict):
        """更新订单数据"""
        self.order_data = order_data
        self.number = order_data.get('number', '')
        self.customer = order_data.get('customer', '')
        self.order_path = order_data.get('path', '')
        self.status = order_data.get('status', '未知')
        
        # 更新状态信息
        self._update_status_from_data(order_data)
        
        # 通知表格更新显示
        if self.table_widget and self.row_index >= 0:
            self.table_widget._update_row_display(self.row_index)
    
    def _update_status_from_data(self, order_data: dict):
        """从服务端数据更新状态信息"""
        # 从服务端数据中提取状态文件夹信息
        status_data = order_data.get('status_data', {})
        self.status_folders = set(status_data.get('status_folders', {}).keys())
        
        # 更新文件数量信息
        self.files_count = {}
        for folder, info in status_data.get('status_folders', {}).items():
            self.files_count[folder] = info.get('file_count', 0)
        
        # 检查是否有文件在第二级
        self.has_files = status_data.get('has_files_in_level2', False)
                
    def get_status_info(self) -> dict:
        """获取状态信息"""
        return {
            'status_folders': list(self.status_folders),
            'files_count': self.files_count.copy(),
            'has_files': getattr(self, 'has_files', False),
            'status': self.status
        }
            


class OrderTableWidget(QWidget):
    """订单记录表格组件"""
    
    # 信号定义
    orders_updated = pyqtSignal(list)  # 订单更新信号
    data_changed = pyqtSignal(dict)  # 数据变化信号
    
    def __init__(self, folder_settings):
        super().__init__()
        self.folder_settings = folder_settings  # 保存folder_settings引用
        self.orders_data = []  # 存储订单数据
        self.current_filter_status = None  # 当前筛选状态
        
        # 订单行对象存储
        self.order_rows = {}  # 存储订单行对象 {order_number: OrderRow}
        
        # 服务端连接相关
        self.websocket_client = None  # WebSocket客户端引用
        
        self.init_ui()
    
    def set_websocket_client(self, websocket_client):
        """设置WebSocket客户端引用"""
        self.websocket_client = websocket_client
    
    def update_orders_data(self, orders_data: list):
        """更新订单数据"""
        self.orders_data = orders_data
        self._update_table_from_data()
        self.orders_updated.emit(orders_data)
    
    def update_order_status_by_id(self, order_id: int, status_data: dict):
        """更新单个订单的状态（通过ID）- 已废弃，请使用 update_order_status_by_number"""
        print(f"⚠️ update_order_status_by_id 已废弃，请使用 update_order_status_by_number")
        return False
    
    def update_order_status_by_number(self, order_number: str, status_data: dict):
        """更新单个订单的状态（通过编号）"""
        try:
            # 查找对应的订单
            for i, order_data in enumerate(self.orders_data):
                if order_data.get('number') == order_number:
                    
                    # 更新状态数据（合并而不是覆盖）
                    if 'status_data' in status_data:
                        # 如果传入的是包装的状态数据
                        order_data['status_data'] = status_data['status_data']
                    else:
                        # 如果传入的是直接的状态数据
                        order_data['status_data'] = status_data
                    
                    # 更新对应的OrderRow对象
                    order_id = order_data.get('id')
                    if order_id and order_id in self.order_rows:
                        self.order_rows[order_id].update_data(order_data)
                        print(f"✅ 已更新OrderRow对象 (ID: {order_id})")
                    else:
                        print(f"⚠️ OrderRow对象不存在 (ID: {order_id})")
                    
                    # 更新表格显示
                    self._update_single_row(i, order_data)
                    print(f"✅ 已更新表格第 {i} 行")
                    
                    print(f"✅ 订单状态更新完成: 编号 {order_number}")
                    return True
            
            print(f"⚠️ 未找到订单: 编号 {order_number}")
            print(f"📋 当前订单列表: {[order.get('number') for order in self.orders_data]}")
            return False
            
        except Exception as e:
            print(f"❌ 更新订单状态失败: {e}")
            import traceback
            traceback.print_exc()
            return False
    
    def remove_order(self, order_id: int):
        """删除单个订单（通过ID）- 已废弃，请使用 remove_order_by_number"""
        print(f"⚠️ remove_order 已废弃，请使用 remove_order_by_number")
        return False
    
    def remove_order_by_number(self, order_number: str):
        """删除单个订单（通过编号）"""
        try:
            print(f"🗑️ 开始删除订单: 编号 {order_number}")
            print(f"📋 当前表格订单数量: {len(self.orders_data)}")
            
            # 查找对应的订单
            for i, order_data in enumerate(self.orders_data):
                if order_data.get('number') == order_number:
                    order_id = order_data.get('id')
                    print(f"✅ 找到订单: {order_data.get('number', '')} - {order_data.get('customer', '')} (ID: {order_id})")
                    
                    # 从数据列表中删除
                    self.orders_data.pop(i)
                    print(f"✅ 已从数据列表删除订单")
                    
                    # 从OrderRow字典中删除
                    if order_number in self.order_rows:
                        del self.order_rows[order_number]
                        print(f"✅ 已从OrderRow字典删除订单")
                    
                    # 重新构建表格
                    self._update_table_from_data()
                    print(f"✅ 已重新构建表格")
                    
                    print(f"✅ 订单删除完成: 编号 {order_number}")
                    return True
            
            print(f"⚠️ 未找到订单: 编号 {order_number}")
            print(f"📋 当前订单列表: {[order.get('number') for order in self.orders_data]}")
            return False
            
        except Exception as e:
            print(f"❌ 删除订单失败: {e}")
            import traceback
            traceback.print_exc()
            return False
    
    def update_order_by_number(self, order_number: str, updated_order: dict):
        """更新单个订单（通过编号）"""
        try:
            print(f"🔄 开始更新订单: 编号 {order_number}")
            print(f"📋 当前表格订单数量: {len(self.orders_data)}")
            
            # 查找对应的订单
            for i, order_data in enumerate(self.orders_data):
                if order_data.get('number') == order_number:
                    print(f"✅ 找到订单: {order_data.get('number', '')} - {order_data.get('customer', '')}")
                    
                    # 比较现有数据和新数据是否完全一致
                    if self._is_order_data_identical(order_data, updated_order):
                        print(f"⏭️ 订单数据完全一致，跳过更新: 编号 {order_number}")
                        return True
                    
                    print(f"🔄 订单数据有变化，开始更新: 编号 {order_number}")
                    
                    # 更新数据
                    self.orders_data[i].update(updated_order)
                    print(f"✅ 已更新数据列表中的订单")
                    
                    # 更新OrderRow字典
                    if order_number in self.order_rows:
                        self.order_rows[order_number].update_data(updated_order)
                        print(f"✅ 已更新OrderRow字典中的订单")
                    
                    # 重新构建表格
                    self._update_table_from_data()
                    print(f"✅ 已重新构建表格")
                    
                    print(f"✅ 订单更新完成: 编号 {order_number}")
                    return True
            
            print(f"⚠️ 未找到订单: 编号 {order_number}")
            print(f"📋 当前订单列表: {[order.get('number') for order in self.orders_data]}")
            
            # 如果订单不存在，尝试添加新订单
            print(f"🔄 尝试添加新订单: {order_number}")
            self.add_new_order(updated_order)
            return True
            
        except Exception as e:
            print(f"❌ 更新订单失败: {e}")
            import traceback
            traceback.print_exc()
            return False
    
    def _is_order_data_identical(self, existing_data: dict, new_data: dict) -> bool:
        """比较两个订单数据是否完全一致"""
        try:
            # 需要比较的关键字段
            key_fields = [
                'number', 'customer', 'product', 'quantity', 'unit_price', 'total_price',
                'priority', 'status', 'pending', 'color', 'direction', 'delivery_date',
                'operator', 'designer', 'proofreader', 'proofread_time', 'note',
                # 添加缺失的关键字段
                'notes', 'is_pending_engraving', 'paper_direction', 'order_taker', 'file_type'
            ]
            
            for field in key_fields:
                existing_value = existing_data.get(field, '')
                new_value = new_data.get(field, '')
                
                # 处理None值
                if existing_value is None:
                    existing_value = ''
                if new_value is None:
                    new_value = ''
                
                # 转换为字符串进行比较
                existing_str = str(existing_value).strip()
                new_str = str(new_value).strip()
                
                if existing_str != new_str:
                    print(f"🔍 字段 '{field}' 不一致: '{existing_str}' vs '{new_str}'")
                    return False
            
            print(f"✅ 订单数据完全一致")
            return True
            
        except Exception as e:
            print(f"❌ 比较订单数据时出错: {e}")
            return False
    
    def _update_table_from_data(self):
        """从数据更新表格显示"""
        # 直接更新表格，避免递归调用
        try:
            # 阻止信号触发（程序更新不触发变更信号）
            self.table.blockSignals(True)
            
            # 清空现有数据
            self.table.setRowCount(0)
            
            if not self.orders_data:
                return
                
            # 设置行数
            self.table.setRowCount(len(self.orders_data))
            
            for row, order_data in enumerate(self.orders_data):
                # 创建订单行对象
                order_number = order_data.get('number', str(row))
                order_row = OrderRow(order_data, self)
                order_row.row_index = row
                self.order_rows[order_number] = order_row
                
                # 更新表格行（这里可以调用现有的表格更新逻辑）
                self._update_single_row(row, order_data)
                
        except Exception as e:
            print(f"更新表格显示失败: {e}")
        finally:
            # 恢复信号触发
            self.table.blockSignals(False)
    
    def _update_single_row(self, row: int, order_data: dict, block_signals: bool = True):
        """更新单个表格行
        
        Args:
            row: 行索引
            order_data: 订单数据
            block_signals: 是否阻止信号触发，默认True（程序更新不触发变更信号）
        """
        try:
            # 阻止信号触发（如果需要）
            should_block = block_signals and not self.table.signalsBlocked()
            if should_block:
                self.table.blockSignals(True)
            
            # 获取基本信息
            number = order_data.get('number', '')
            customer = order_data.get('customer', '')
            status_data = order_data.get('status_data', {})
            
            # 完成列 - 可点击的按钮
            complete_btn = QPushButton("未完成")
            complete_btn.setObjectName("complete_btn")
            complete_btn.setFlat(True)
            complete_btn.setCheckable(True)
            complete_btn.setChecked(order_data.get('is_completed', False))
            complete_btn.clicked.connect(lambda checked, r=row: self._on_complete_clicked(r, checked))
            self._update_complete_button_style(row, order_data.get('is_completed', False))
            self.table.setCellWidget(row, 0, complete_btn)
            
            # 开头列 - 显示订单编号的开头数字（只读）
            start_digit = number[0] if number else ""
            start_item = QTableWidgetItem(start_digit)
            start_item.setFlags(start_item.flags() & ~Qt.ItemFlag.ItemIsEditable)  # 设置为只读
            self.table.setItem(row, 1, start_item)
            
            # 编号列（只读）
            number_item = QTableWidgetItem(number)
            number_item.setFlags(number_item.flags() & ~Qt.ItemFlag.ItemIsEditable)  # 设置为只读
            self.table.setItem(row, 2, number_item)
            
            # 客户名称列（只读）
            customer_item = QTableWidgetItem(customer)
            customer_item.setFlags(customer_item.flags() & ~Qt.ItemFlag.ItemIsEditable)  # 设置为只读
            self.table.setItem(row, 3, customer_item)
            
            # 更新状态按钮
            self._add_status_buttons(row, order_data)
            
            # 优先等级列（列索引从8改为9）
            priority = order_data.get('priority', '中级')
            priority_combo = QComboBox()
            priority_combo.addItems(["低级", "中级", "高级"])
            priority_combo.setCurrentText(priority)
            priority_combo.currentTextChanged.connect(lambda text, r=row: self._on_priority_changed(r, text))
            self.table.setCellWidget(row, 9, priority_combo)
            
            # 客户备注列（列索引从9改为10）
            notes = order_data.get('notes', '')
            self.table.setItem(row, 10, QTableWidgetItem(notes))
            
            # 是否挂版列 - 下拉框（列索引从10改为11）
            pending_combo = QComboBox()
            pending_combo.addItems(["是", "否"])
            pending_combo.setCurrentText("是" if order_data.get('is_pending_engraving', False) else "否")
            pending_combo.currentTextChanged.connect(lambda text, r=row: self._on_pending_changed(r, text))
            
            # 设置背景色
            is_pending = order_data.get('is_pending_engraving', False)
            if is_pending:
                pending_combo.setStyleSheet("QComboBox { background-color: red; color: white; }")
            else:
                pending_combo.setStyleSheet("QComboBox { background-color: white; color: black; }")
            
            self.table.setCellWidget(row, 11, pending_combo)
            
            # 颜色列 - 下拉框（列索引从11改为12）
            color_combo = QComboBox()
            color_combo.addItems(['', '单黑', '双色', '三色', '四色'])
            if is_pending:
                color = order_data.get('color', '单黑')
                color_combo.setCurrentText(color)
            else:
                color_combo.setCurrentText('')  # 非挂版时显示空白
            color_combo.setEnabled(is_pending)  # 根据挂版状态启用/禁用
            color_combo.currentTextChanged.connect(lambda text, r=row: self._on_color_changed(r, text))
            self.table.setCellWidget(row, 12, color_combo)
            
            # 进纸方向列 - 下拉框（列索引从12改为13）
            direction_combo = QComboBox()
            direction_combo.addItems(['', '上下', '左右'])
            if is_pending:
                paper_direction = order_data.get('paper_direction', '上下')
                direction_combo.setCurrentText(paper_direction)
            else:
                direction_combo.setCurrentText('')  # 非挂版时显示空白
            direction_combo.setEnabled(is_pending)  # 根据挂版状态启用/禁用
            direction_combo.currentTextChanged.connect(lambda text, r=row: self._on_paper_direction_changed(r, text))
            self.table.setCellWidget(row, 13, direction_combo)
            
            # 文件类型列 - 下拉框（列索引从13改为14）
            file_type_combo = QComboBox()
            file_type_combo.addItems(['PDF', 'CDR'])
            file_type = order_data.get('file_type', 'PDF')
            file_type_combo.setCurrentText(file_type)
            file_type_combo.currentTextChanged.connect(lambda text, r=row: self._on_file_type_changed(r, text))
            self.table.setCellWidget(row, 14, file_type_combo)
            
            # 交货日期列 - 日期选择控件（列索引从14改为15）
            date_edit = QDateEdit()
            date_edit.setCalendarPopup(True)
            date_edit.setDisplayFormat("yyyy-MM-dd")
            # 设置默认日期为今天
            from PyQt6.QtCore import QDate
            date_edit.setDate(QDate.currentDate())
            # 如果有交货日期数据，设置相应日期
            delivery_date = order_data.get('delivery_date', '')
            if delivery_date and delivery_date != '当天':
                try:
                    # 尝试解析日期字符串
                    if '-' in delivery_date:
                        date_parts = delivery_date.split('-')
                        if len(date_parts) == 3:
                            year, month, day = map(int, date_parts)
                            date_edit.setDate(QDate(year, month, day))
                except:
                    pass
            date_edit.dateChanged.connect(lambda date, r=row: self._on_delivery_date_changed(r, date))
            self.table.setCellWidget(row, 15, date_edit)
            
            # 接单人列 - 下拉框（列索引从15改为16）
            order_taker = order_data.get('order_taker', '1号客服')
            order_taker_combo = QComboBox()
            order_taker_combo.addItems(["1号客服", "2号客服", "3号客服"])
            order_taker_combo.setCurrentText(order_taker)
            order_taker_combo.currentTextChanged.connect(lambda text, r=row: self._on_order_taker_changed(r, text))
            self.table.setCellWidget(row, 16, order_taker_combo)
            
            # 设计人列 - 下拉框（列索引从16改为17）
            designer = order_data.get('designer', '拼版1号')
            designer_combo = QComboBox()
            designer_combo.addItems(["拼版1号", "拼版2号", "外发1号", "外发2号", "外发3号", "外发4号"])
            designer_combo.setCurrentText(designer)
            designer_combo.currentTextChanged.connect(lambda text, r=row: self._on_designer_changed(r, text))
            self.table.setCellWidget(row, 17, designer_combo)
            
            # 校对人列 - 可编辑，变化时自动更新校对时间（列索引从17改为18）
            proofreader = order_data.get('proofreader', '')
            proofreader_item = QTableWidgetItem(proofreader)
            proofreader_item.setFlags(proofreader_item.flags() | Qt.ItemFlag.ItemIsEditable)  # 设置为可编辑
            self.table.setItem(row, 18, proofreader_item)
            
            # 校对时间列 - 只读，由校对人变化自动更新（列索引从18改为19）
            proofreading_time = order_data.get('proofreading_time', '')
            proofreading_time_item = QTableWidgetItem(proofreading_time)
            proofreading_time_item.setFlags(proofreading_time_item.flags() & ~Qt.ItemFlag.ItemIsEditable)  # 设置为只读
            self.table.setItem(row, 19, proofreading_time_item)
            
            # 更新状态按钮颜色（如果有状态数据）
            if status_data:
                # 更新其他状态按钮（未确认、挂、已做）
                status_folders = status_data.get('status_folders', {})
                for folder_name, folder_info in status_folders.items():
                    has_files = folder_info.get('has_files', False)
                    self._update_status_button_color(row, folder_name, has_files)
                
                # 更新未刻版按钮状态（检查订单目录下是否有文件）
                not_engraved_status = status_data.get('not_engraved', {})
                has_files_in_order_dir = not_engraved_status.get('has_files', False)
                self._update_not_engraved_button(row, has_files_in_order_dir)
                
                # 更新固态按钮状态（检查固态目录下是否有文件）
                solid_state_status = status_data.get('solid_state', {})
                has_files_in_solid_dir = solid_state_status.get('has_files', False)
                self._update_solid_state_button(row, has_files_in_solid_dir)
            
            # 检查并更新完成按钮状态（确保所有按钮更新后再检查）
            self._check_and_update_complete_button(row)
            
            print(f"✅ 已更新表格行 {row}: {number} - {customer}")
            
        except Exception as e:
            print(f"❌ 更新行 {row} 失败: {e}")
            import traceback
            traceback.print_exc()
        finally:
            # 恢复信号触发（只在本函数阻止了信号时才恢复）
            if should_block:
                self.table.blockSignals(False)
    
    def _add_order_row_to_table(self, order_row: OrderRow, row_index: int):
        """将订单行添加到表格中"""
        # 这里需要根据实际的表格结构来实现
        # 暂时留空，需要根据具体的表格列来实现
        pass
    
    def _update_row_display(self, row_index: int):
        """更新指定行的显示"""
        if row_index < 0 or row_index >= self.table.rowCount():
            return
        
        # 更新表格行的显示内容
        # 这里需要根据实际的表格结构来实现
        pass
    
    def _update_row_status_buttons(self, row_index: int, status_folders: List[str]):
        """更新指定行的状态按钮"""
        if row_index < 0 or row_index >= self.table.rowCount():
            return
        
        # 更新状态按钮的显示
        # 这里需要根据实际的表格结构来实现
        pass
    
        
    def init_ui(self):
        """初始化用户界面"""
        layout = QVBoxLayout(self)
        layout.setSpacing(8)
        layout.setContentsMargins(0, 0, 0, 0)
        
        # 创建标题
        title_label = QLabel("订单记录")
        title_label.setObjectName("section_title")
        layout.addWidget(title_label)
        
        # 创建筛选控制区域
        filter_frame = QFrame()
        filter_frame.setObjectName("filter_frame")
        filter_layout = QHBoxLayout(filter_frame)
        filter_layout.setSpacing(15)  # 增加组之间的间距
        filter_layout.setContentsMargins(15, 10, 15, 10)
        
        # 数字标签页组（互斥选择，紧密排列）
        number_group = QHBoxLayout()
        number_group.setSpacing(0)  # 组内按钮无间距
        self.number_buttons = []
        for i in range(1, 7):
            tab_btn = QPushButton(str(i))
            tab_btn.setObjectName("number_tab")
            tab_btn.setCheckable(True)
            tab_btn.clicked.connect(lambda checked, num=str(i): self._on_number_tab_clicked(num, checked))
            self.number_buttons.append(tab_btn)
            number_group.addWidget(tab_btn)
        filter_layout.addLayout(number_group)
        
        # 完成状态组（互斥，紧密排列）
        completion_group = QHBoxLayout()
        completion_group.setSpacing(0)  # 组内按钮无间距
        self.completion_buttons = []
        completion_tabs = ["已完成", "未完成"]
        for status in completion_tabs:
            status_btn = QPushButton(status)
            status_btn.setObjectName("status_tab")
            status_btn.setCheckable(True)
            status_btn.clicked.connect(lambda checked, s=status: self._on_completion_tab_clicked(s, checked))
            self.completion_buttons.append(status_btn)
            completion_group.addWidget(status_btn)
        filter_layout.addLayout(completion_group)
        
        # 优先级组（互斥，紧密排列）
        priority_group = QHBoxLayout()
        priority_group.setSpacing(0)  # 组内按钮无间距
        self.priority_buttons = []
        priority_tabs = ["中级", "高级"]
        for status in priority_tabs:
            status_btn = QPushButton(status)
            status_btn.setObjectName("status_tab")
            status_btn.setCheckable(True)
            status_btn.clicked.connect(lambda checked, s=status: self._on_priority_tab_clicked(s, checked))
            self.priority_buttons.append(status_btn)
            priority_group.addWidget(status_btn)
        filter_layout.addLayout(priority_group)
        
        # 其他状态按钮组（非互斥，紧密排列）
        other_group = QHBoxLayout()
        other_group.setSpacing(0)  # 组内按钮无间距
        other_tabs = ["固态", "未刻版", "未确认", "挂", "已做", "挂版"]
        for status in other_tabs:
            status_btn = QPushButton(status)
            status_btn.setObjectName("status_tab")
            status_btn.setCheckable(True)
            status_btn.clicked.connect(lambda checked, s=status: self._on_status_tab_clicked(s, checked))
            other_group.addWidget(status_btn)
        filter_layout.addLayout(other_group)
        
        # 客户筛选
        customer_label = QLabel("客户筛选:")
        customer_label.setObjectName("filter_label")
        filter_layout.addWidget(customer_label)
        
        self.customer_input = QLineEdit()
        self.customer_input.setObjectName("customer_input")
        self.customer_input.setPlaceholderText("输入客户名称进行筛选...")
        self.customer_input.textChanged.connect(self._on_customer_filter_changed)
        filter_layout.addWidget(self.customer_input)
        
        # 右侧按钮
        filter_layout.addStretch()
        
        layout.addWidget(filter_frame)
        
        # 创建表格
        self.table = QTableWidget()
        self.table.setObjectName("order_table")
        self.setup_table()
        layout.addWidget(self.table)
        
    def setup_table(self):
        """设置表格"""
        # 设置列
        headers = [
            "完成", "开头", "编号", "客户名称", "固态", "未刻版",
            "未确认", "挂", "已做", "优先等级", "客户备注", "是否挂版", 
            "颜色", "进纸方向", "文件类型", "交货日期", "接单人", "设计人", "校对人", "校对时间"
        ]
        self.table.setColumnCount(len(headers))
        self.table.setHorizontalHeaderLabels(headers)
        
        # 设置表格属性
        self.table.setAlternatingRowColors(True)
        self.table.setSelectionBehavior(QTableWidget.SelectionBehavior.SelectRows)
        self.table.setSelectionMode(QTableWidget.SelectionMode.SingleSelection)
        self.table.verticalHeader().setDefaultSectionSize(30)  # 设置行高
        
        # 设置列宽
        header = self.table.horizontalHeader()
        header.setSectionResizeMode(0, QHeaderView.ResizeMode.Fixed)  # 完成列
        header.setSectionResizeMode(1, QHeaderView.ResizeMode.Fixed)  # 开头列
        header.setSectionResizeMode(2, QHeaderView.ResizeMode.Fixed)  # 编号列
        header.setSectionResizeMode(3, QHeaderView.ResizeMode.ResizeToContents)  # 客户名称
        header.setSectionResizeMode(4, QHeaderView.ResizeMode.Fixed)  # 未刻版
        header.setSectionResizeMode(5, QHeaderView.ResizeMode.Fixed)  # 固态
        header.setSectionResizeMode(6, QHeaderView.ResizeMode.Fixed)  # 未确认
        header.setSectionResizeMode(7, QHeaderView.ResizeMode.Fixed)  # 挂
        header.setSectionResizeMode(8, QHeaderView.ResizeMode.Fixed)  # 已做
        header.setSectionResizeMode(9, QHeaderView.ResizeMode.Fixed)  # 优先等级
        header.setSectionResizeMode(10, QHeaderView.ResizeMode.Stretch)  # 客户备注
        header.setSectionResizeMode(11, QHeaderView.ResizeMode.Fixed)  # 是否挂版
        header.setSectionResizeMode(12, QHeaderView.ResizeMode.Fixed)  # 颜色
        header.setSectionResizeMode(13, QHeaderView.ResizeMode.Fixed)  # 进纸方向
        header.setSectionResizeMode(14, QHeaderView.ResizeMode.Fixed)  # 文件类型
        header.setSectionResizeMode(15, QHeaderView.ResizeMode.Fixed)  # 交货日期
        header.setSectionResizeMode(16, QHeaderView.ResizeMode.Fixed)  # 接单人
        header.setSectionResizeMode(17, QHeaderView.ResizeMode.Fixed)  # 设计人
        header.setSectionResizeMode(18, QHeaderView.ResizeMode.Fixed)  # 校对人
        header.setSectionResizeMode(19, QHeaderView.ResizeMode.Fixed)  # 校对时间
        
        # 设置固定列宽
        self.table.setColumnWidth(0, 50)   # 完成列
        self.table.setColumnWidth(1, 50)   # 开头列
        self.table.setColumnWidth(2, 60)   # 编号列
        self.table.setColumnWidth(4, 70)   # 固态
        self.table.setColumnWidth(5, 70)   # 未刻版
        self.table.setColumnWidth(6, 70)   # 未确认
        self.table.setColumnWidth(7, 50)   # 挂
        self.table.setColumnWidth(8, 50)   # 已做
        self.table.setColumnWidth(9, 80)   # 优先等级
        self.table.setColumnWidth(11, 70)  # 是否挂版
        self.table.setColumnWidth(12, 70)  # 颜色
        self.table.setColumnWidth(13, 80)  # 进纸方向
        self.table.setColumnWidth(14, 80)  # 文件类型
        self.table.setColumnWidth(15, 100)  # 交货日期
        self.table.setColumnWidth(16, 80)  # 接单人
        self.table.setColumnWidth(17, 80)  # 设计人
        self.table.setColumnWidth(18, 60)  # 校对人
        self.table.setColumnWidth(19, 100) # 校对时间
        
        # 连接表格单元格变化信号
        self.table.itemChanged.connect(self._on_table_item_changed)
                     
    def update_orders_from_parser(self, orders_info):
        """从解析器更新订单数据"""
        try:
            # 阻止信号触发（程序更新不触发变更信号）
            self.table.blockSignals(True)
            
            # 清空现有数据
            self.table.setRowCount(0)
            self.orders_data.clear()
            
            if not orders_info:
                return
                
            # 设置行数
            self.table.setRowCount(len(orders_info))
            
            for row, order_info in enumerate(orders_info):
                # 处理order_info可能是字典或对象的情况
                if isinstance(order_info, dict):
                    # 如果是字典，直接使用
                    number = order_info.get('number', '')
                    customer = order_info.get('customer', '')
                    path = order_info.get('path', '')
                    order_id = order_info.get('id', 0)
                else:
                    # 如果是对象，使用属性访问
                    number = getattr(order_info, 'number', '')
                    customer = getattr(order_info, 'customer', '')
                    path = getattr(order_info, 'path', '')
                    order_id = getattr(order_info, 'id', 0)
                
                # 创建订单数据
                order_data = {
                    'id': int(order_id) if order_id else (int(number) if number.isdigit() else 0),
                    'number': number,
                    'customer': customer,
                    'path': path,
                    'is_selected': False,
                    'is_completed': False,
                    'not_engraved': True,
                    'solid_state': False,
                    'not_confirmed': True,
                    'pending': True,
                    'done': False,
                    'priority': '中级',
                    'notes': '',
                    'is_pending_engraving': False,
                    'color': '单黑',
                    'paper_direction': '上下',
                    'file_type': 'PDF',
                    'delivery_date': '当天',
                    'order_taker': '1号客服',
                    'designer': '拼版1号',
                    'proofreader': '',
                    'proofreading_time': ''
                }
                
                self.orders_data.append(order_data)
                
                # 完成列 - 复选框
                complete_checkbox = QCheckBox()
                complete_checkbox.setChecked(order_data['is_completed'])
                self.table.setCellWidget(row, 0, complete_checkbox)
                
                # 开头列 - 使用序号
                self.table.setItem(row, 1, QTableWidgetItem(str(row + 1)))
                
                # 编号列 - 使用编号
                self.table.setItem(row, 2, QTableWidgetItem(number))
                
                # 客户名称列
                self.table.setItem(row, 3, QTableWidgetItem(customer))
                
                # 状态按钮列
                self._add_status_buttons(row, order_data)
                
                # 其他列
                self.table.setItem(row, 8, QTableWidgetItem(order_data['priority']))
                self.table.setItem(row, 9, QTableWidgetItem(order_data['notes']))
                
                # 是否挂版列
                item = QTableWidgetItem("是" if order_data['is_pending_engraving'] else "否")
                if order_data['is_pending_engraving']:
                    item.setBackground(Qt.GlobalColor.red)
                else:
                    item.setBackground(Qt.GlobalColor.white)
                self.table.setItem(row, 10, item)
                
                # 文件类型列
                self.table.setItem(row, 13, QTableWidgetItem(order_data.get('file_type', 'PDF')))
                
                # 交货日期列
                self.table.setItem(row, 14, QTableWidgetItem(order_data['delivery_date']))
                
                # 接单人列 - 下拉框
                order_taker = order_data.get('order_taker', '1号客服')
                order_taker_combo = QComboBox()
                order_taker_combo.addItems(["1号客服", "2号客服", "3号客服"])
                order_taker_combo.setCurrentText(order_taker)
                order_taker_combo.currentTextChanged.connect(lambda text, r=row: self._on_order_taker_changed(r, text))
                self.table.setCellWidget(row, 15, order_taker_combo)
                
                # 设计人列 - 下拉框
                designer = order_data.get('designer', '拼版1号')
                designer_combo = QComboBox()
                designer_combo.addItems(["拼版1号", "拼版2号", "外发1号", "外发2号", "外发3号", "外发4号"])
                designer_combo.setCurrentText(designer)
                designer_combo.currentTextChanged.connect(lambda text, r=row: self._on_designer_changed(r, text))
                self.table.setCellWidget(row, 16, designer_combo)
                
                # 校对人和校对时间列
                self.table.setItem(row, 17, QTableWidgetItem(order_data['proofreader']))
                self.table.setItem(row, 18, QTableWidgetItem(order_data['proofreading_time']))
                
            # 发送订单更新信号
            self.orders_updated.emit(self.orders_data)
            
        except Exception as e:
            QMessageBox.warning(self, "更新订单失败", f"更新订单数据时发生错误: {str(e)}")
        finally:
            # 恢复信号触发
            self.table.blockSignals(False)
            
        # 重新应用当前筛选
        if self.current_filter_status:
            self._apply_status_filter()
            
    def _add_status_buttons(self, row, order_data):
        """添加状态按钮"""
        # 获取订单路径信息
        order_path = order_data.get('path', '')
        order_number = order_data.get('number', '')
        customer = order_data.get('customer', '')

        order_folder = order_path.split("\\")[-1] if order_path else ""
        
        # 固态按钮（第4列）
        btn_solid = QPushButton("固态")
        btn_solid.setObjectName("solid_state_btn")
        btn_solid.setFlat(True)  # 设置扁平样式
        btn_solid.clicked.connect(lambda: self._open_folder(order_folder, "固态"))
        self.table.setCellWidget(row, 4, btn_solid)
        
        # 未刻版按钮（第5列）
        btn1 = QPushButton("未刻版")
        btn1.setObjectName("not_engraved_btn")
        btn1.setFlat(True)  # 设置扁平样式
        btn1.clicked.connect(lambda: self._open_folder(order_folder, ""))
        self.table.setCellWidget(row, 5, btn1)
        
        # 未确认按钮（列索引从5改为6）
        btn2 = QPushButton("未确认")
        btn2.setObjectName("not_confirmed_btn")
        btn2.setFlat(True)  # 设置扁平样式
        btn2.clicked.connect(lambda: self._open_folder(order_folder, "未确认"))
        self.table.setCellWidget(row, 6, btn2)
        
        # 挂按钮（列索引从6改为7）
        btn3 = QPushButton("挂")
        btn3.setObjectName("pending_btn")
        btn3.setFlat(True)  # 设置扁平样式
        btn3.clicked.connect(lambda: self._open_folder(order_folder, "挂"))
        self.table.setCellWidget(row, 7, btn3)
        
        # 已做按钮（列索引从7改为8）
        btn4 = QPushButton("已做")
        btn4.setObjectName("confirmed_btn")
        btn4.setFlat(True)  # 设置扁平样式
        btn4.clicked.connect(lambda: self._open_folder(order_folder, "已做"))
        self.table.setCellWidget(row, 8, btn4)
        
    def _get_main_window(self):
        """获取主窗口引用"""
        parent = self.parent()
        while parent:
            if hasattr(parent, 'server_ip_input'):
                return parent
            parent = parent.parent()
        return None
    
    def _open_folder(self, order_path: str, status_folder: str):
        """打开对应的文件夹"""
        try:
            # 从主窗口获取服务器IP地址
            main_window = self._get_main_window()
            if main_window and hasattr(main_window, 'server_ip_input'):
                ip_address = main_window.server_ip_input.text().strip()
            else:
                # 如果无法获取主窗口，尝试从配置文件读取
                import configparser
                config_file = "settings.ini"
                ip_address = ""
                if os.path.exists(config_file):
                    try:
                        config = configparser.ConfigParser()
                        config.read(config_file, encoding='utf-8')
                        if config.has_option('Settings', 'server_ip'):
                            ip_address = config.get('Settings', 'server_ip').strip()
                    except Exception:
                        pass
            
            # 获取共享文件夹配置
            shared_folder = self.folder_settings.path_input.text().strip()
            
            if not ip_address:
                QMessageBox.warning(self, "配置错误", "请先配置服务器IP地址")
                return
                
            if not shared_folder:
                QMessageBox.warning(self, "配置错误", "请先配置共享文件夹名")
                return
            
            # 获取当前日期
            from datetime import datetime
            today = datetime.now()
            date_str = f"{today.month}.{today.day}"
            
            # 构建网络共享路径: \\ip\共享文件夹名\日期\订单路径\状态文件夹
            if order_path:
                # 如果有订单路径，构建完整路径
                full_path = f"\\\\{ip_address}\\{shared_folder}\\{date_str}\\{order_path}\\{status_folder}"
            else:
                # 如果没有订单路径，只到日期目录
                full_path = f"\\\\{ip_address}\\{shared_folder}\\{date_str}"
            
            print(f"📁 尝试打开网络共享文件夹: {full_path}")
            
            # 对于网络共享路径，不检查是否存在，直接尝试打开
            print(f"✅ 正在打开资源管理器: {full_path}")
            
            # 使用 QDesktopServices 打开文件夹（跨平台，无需子进程）
            # 对于 UNC 路径（网络共享路径），需要特殊处理
            if full_path.startswith('\\\\'):
                # UNC 路径格式: \\server\share\path
                # 转换为 file:// 格式: file://server/share/path
                # 注意：UNC 路径需要保留开头的两个斜杠
                unc_path = full_path.replace('\\', '/')
                url = QUrl(f"file://{unc_path}")
            else:
                # 本地路径使用 fromLocalFile
                url = QUrl.fromLocalFile(full_path)
            
            # 打开文件夹
            if not QDesktopServices.openUrl(url):
                QMessageBox.warning(self, "打开失败", 
                    f"无法打开文件夹: {full_path}\n"
                    f"请检查:\n"
                    f"1. 路径是否正确\n"
                    f"2. 网络连接是否正常\n"
                    f"3. 是否有访问权限")
                
        except Exception as e:
            QMessageBox.critical(self, "错误", f"打开文件夹时发生错误: {str(e)}")
    
    def _on_number_tab_clicked(self, number: str, checked: bool):
        """数字标签页点击事件（按开头数字筛选，互斥选择）"""
        if checked:
            # 取消其他数字按钮的选中状态
            for btn in self.number_buttons:
                if btn.text() != number:
                    btn.setChecked(False)
            
            # 设置当前筛选状态
            self.current_filter_status = f"开头{number}"
            self._apply_number_filter(number)
        else:
            # 如果取消选中，清除筛选
            self.current_filter_status = None
            self._clear_number_filter()
    
    def _on_completion_tab_clicked(self, status: str, checked: bool):
        """完成状态标签页点击事件（互斥选择）"""
        if checked:
            # 取消其他完成状态按钮的选中状态
            for btn in self.completion_buttons:
                if btn.text() != status:
                    btn.setChecked(False)
            
            # 设置当前筛选状态
            self.current_filter_status = status
            self._apply_status_filter()
        else:
            # 如果取消选中，清除筛选
            self.current_filter_status = None
            self._clear_status_filter()
    
    def _on_priority_tab_clicked(self, status: str, checked: bool):
        """优先级标签页点击事件（互斥选择）"""
        if checked:
            # 取消其他优先级按钮的选中状态
            for btn in self.priority_buttons:
                if btn.text() != status:
                    btn.setChecked(False)
            
            # 设置当前筛选状态
            self.current_filter_status = status
            self._apply_status_filter()
        else:
            # 如果取消选中，清除筛选
            self.current_filter_status = None
            self._clear_status_filter()
    
    def _on_status_tab_clicked(self, status: str, checked: bool):
        """其他状态标签页点击事件（非互斥）"""
        if checked:
            # 如果选中，设置当前筛选状态
            self.current_filter_status = status
            self._apply_status_filter()
        else:
            # 如果取消选中，清除筛选
            self.current_filter_status = None
            self._clear_status_filter()
    
    def _apply_status_filter(self):
        """应用状态筛选"""
        self._apply_all_filters()
    
    def _clear_status_filter(self):
        """清除状态筛选"""
        self._apply_all_filters()
    
    def _update_complete_button_style(self, row: int, is_completed: bool):
        """更新完成按钮样式"""
        try:
            if row < 0 or row >= self.table.rowCount():
                return
            
            # 阻止信号触发（程序更新样式不触发变更信号）
            should_block = not self.table.signalsBlocked()
            if should_block:
                self.table.blockSignals(True)
                
            widget = self.table.cellWidget(row, 0)
            if widget:
                if is_completed:
                    # 已完成时变绿
                    widget.setChecked(True)
                    widget.setText("已完成")
                else:
                    # 未完成时变透明
                    widget.setChecked(False)
                    widget.setText("未完成")
            
            # 恢复信号触发
            if should_block:
                self.table.blockSignals(False)
                    
        except Exception as e:
            print(f"更新完成按钮样式失败: {e}")
            # 确保异常时也恢复信号
            if should_block:
                self.table.blockSignals(False)
    
    def _on_complete_clicked(self, row: int, checked: bool):
        """完成按钮点击事件"""
        try:
            if row < 0 or row >= len(self.orders_data):
                return
            
            # 检查固态、未刻版、未确认、挂这4个按钮，任何一个为红色时都不允许点击完成
            buttons_to_check = [
                (4, "固态"),
                (5, "未刻版"),
                (6, "未确认"),
                (7, "挂")
            ]
            
            for col_index, button_name in buttons_to_check:
                status_btn = self.table.cellWidget(row, col_index)
                if status_btn:
                    style = status_btn.styleSheet()
                    if "background-color: #f44336" in style:
                        # 按钮为红色时，强制完成按钮为未选中状态
                        complete_btn = self.table.cellWidget(row, 0)
                        if complete_btn:
                            complete_btn.setChecked(False)
                        print(f"⚠️ {button_name}为红色时，无法点击完成按钮")
                        QMessageBox.warning(self, "无法完成", f"{button_name}状态为红色，请先处理完成后再标记为已完成")
                        return
                
            # 更新订单数据
            order_data = self.orders_data[row]
            order_data['is_completed'] = checked
            
            # 更新按钮样式
            self._update_complete_button_style(row, checked)
            
            # 发送状态更新到服务端
            if self.websocket_client and self.websocket_client.is_connected():
                self.websocket_client.update_order_status(order_data['number'], {'is_completed': checked})
            
            print(f"✅ 订单 {order_data['number']} 完成状态更新为: {checked}")
            
        except Exception as e:
            print(f"❌ 更新完成状态失败: {e}")
    
    def _disable_complete_button(self, row: int):
        """禁用完成按钮"""
        try:
            complete_btn = self.table.cellWidget(row, 0)
            if complete_btn:
                complete_btn.setEnabled(False)
                complete_btn.setChecked(False)
                self._update_complete_button_style(row, False)
                print(f"🔒 行 {row} 完成按钮已禁用（未刻版为红色）")
        except Exception as e:
            print(f"禁用完成按钮失败: {e}")
    
    def _enable_complete_button(self, row: int):
        """启用完成按钮"""
        try:
            complete_btn = self.table.cellWidget(row, 0)
            if complete_btn:
                complete_btn.setEnabled(True)
        except Exception as e:
            print(f"启用完成按钮失败: {e}")
    
    def _apply_number_filter(self, number: str):
        """应用数字筛选（按开头数字）"""
        self._apply_all_filters()
    
    def _clear_number_filter(self):
        """清除数字筛选"""
        self._apply_all_filters()
    
    def _should_show_row_by_number(self, row: int, number: str) -> bool:
        """判断行是否应该显示（按开头数字）"""
        if not self.orders_data or row >= len(self.orders_data):
            return True
            
        order_data = self.orders_data[row]
        order_number = order_data.get('number', '')
        
        # 检查订单编号是否以指定数字开头
        return order_number.startswith(number)
    
    def _on_customer_filter_changed(self, text: str):
        """客户筛选文本变化事件"""
        try:
            # 应用客户筛选
            self._apply_customer_filter(text)
        except Exception as e:
            print(f"❌ 客户筛选失败: {e}")
    
    def _apply_customer_filter(self, customer_text: str):
        """应用客户筛选"""
        # 重新应用所有筛选条件
        self._apply_all_filters()
    
    def _apply_all_filters(self):
        """应用所有筛选条件"""
        for row in range(self.table.rowCount()):
            should_show = True
            
            # 应用数字筛选
            if hasattr(self, 'current_filter_status') and self.current_filter_status and self.current_filter_status.startswith("开头"):
                number = self.current_filter_status.replace("开头", "")
                should_show = should_show and self._should_show_row_by_number(row, number)
            
            # 应用状态筛选
            if hasattr(self, 'current_filter_status') and self.current_filter_status and not self.current_filter_status.startswith("开头"):
                should_show = should_show and self._should_show_row(row, self.current_filter_status)
            
            # 应用客户筛选
            customer_text = self.customer_input.text().strip()
            if customer_text:
                should_show = should_show and self._should_show_row_by_customer(row, customer_text)
            
            self.table.setRowHidden(row, not should_show)
    
    def _should_show_row_by_customer(self, row: int, customer_text: str) -> bool:
        """判断行是否应该显示（按客户名称）"""
        if not self.orders_data or row >= len(self.orders_data):
            return True
            
        order_data = self.orders_data[row]
        customer = order_data.get('customer', '')
        
        # 检查客户名称是否包含输入文本（不区分大小写）
        return customer_text.lower() in customer.lower()
    
    def _should_show_row(self, row: int, status: str) -> bool:
        """判断行是否应该显示"""
        if not self.orders_data or row >= len(self.orders_data):
            return True
            
        # 对于状态按钮，根据按钮的实际背景色判断
        if status in ["固态", "未刻版", "未确认", "挂", "已做"]:
            return self._is_button_colored(row, status)
        
        # 其他状态仍基于订单数据
        order_data = self.orders_data[row]
        
        if status == "已完成":
            return order_data.get('is_completed', False)
        elif status == "未完成":
            return not order_data.get('is_completed', False)
        elif status == "中级":
            return order_data.get('priority', '') == '中级'
        elif status == "高级":
            return order_data.get('priority', '') == '高级'
        elif status == "挂版":
            return order_data.get('is_pending_engraving', False)
        
        return True
    
    def _is_button_colored(self, row: int, status: str) -> bool:
        """检查按钮是否有背景色（非透明）"""
        try:
            # 根据状态获取对应的列索引
            column_map = {
                "固态": 4,
                "未刻版": 5,
                "未确认": 6, 
                "挂": 7,
                "已做": 8
            }
            
            col = column_map.get(status)
            if col is None:
                return True
                
            # 获取按钮控件
            button = self.table.cellWidget(row, col)
            if not button:
                return False
                
            # 获取按钮的样式表
            style_sheet = button.styleSheet()
            
            # 检查是否包含背景色设置
            if "background-color:" in style_sheet:
                # 检查是否为透明
                if "background-color: transparent" in style_sheet:
                    return False
                # 检查是否有具体的颜色值
                import re
                bg_match = re.search(r'background-color:\s*([^;]+)', style_sheet)
                if bg_match:
                    color = bg_match.group(1).strip()
                    return color != "transparent" and color != ""
            
            return False
            
        except Exception as e:
            print(f"检查按钮颜色错误: {e}")
            return False
    
    def add_new_order(self, order_data):
        """添加新订单到表格"""
        try:
            order_number = order_data.get('number', '')
            
            # 检查是否已存在相同编号的订单
            existing_order_index = None
            for i, existing_order in enumerate(self.orders_data):
                if existing_order.get('number') == order_number:
                    existing_order_index = i
                    break
            
            if existing_order_index is not None:
                # 如果已存在，更新现有订单
                self.orders_data[existing_order_index].update(order_data)
                print(f"🔄 订单已存在，更新信息: {order_number}")
                
                # 更新表格显示
                self._update_single_row(existing_order_index, self.orders_data[existing_order_index])
                return

            # 阻止信号触发（程序更新不触发变更信号）
            self.table.blockSignals(True)
            
            # 如果不存在，添加新订单
            # 创建新的订单行
            row = self.table.rowCount()
            self.table.insertRow(row)
            
            # 添加订单数据
            self.orders_data.append(order_data)
            
            # 完成列 - 复选框
            complete_checkbox = QCheckBox()
            complete_checkbox.setChecked(order_data.get('is_completed', False))
            self.table.setCellWidget(row, 0, complete_checkbox)
            
            # 开头列 - 显示订单编号的开头数字（只读）
            number = order_data.get('number', '')
            start_digit = number[0] if number else ""
            start_item = QTableWidgetItem(start_digit)
            start_item.setFlags(start_item.flags() & ~Qt.ItemFlag.ItemIsEditable)  # 设置为只读
            self.table.setItem(row, 1, start_item)
            
            # 编号列 - 使用编号（只读）
            number_item = QTableWidgetItem(order_data.get('number', ''))
            number_item.setFlags(number_item.flags() & ~Qt.ItemFlag.ItemIsEditable)  # 设置为只读
            self.table.setItem(row, 2, number_item)
            
            # 客户名称列（只读）
            customer_item = QTableWidgetItem(order_data.get('customer', ''))
            customer_item.setFlags(customer_item.flags() & ~Qt.ItemFlag.ItemIsEditable)  # 设置为只读
            self.table.setItem(row, 3, customer_item)
            
            # 状态按钮列
            self._add_status_buttons(row, order_data)
            
            # 更新状态按钮颜色（如果有状态数据）
            status_data = order_data.get('status_data', {})
            if status_data:
                # 更新其他状态按钮（未确认、挂、已做）
                status_folders = status_data.get('status_folders', {})
                for folder_name, folder_info in status_folders.items():
                    has_files = folder_info.get('has_files', False)
                    self._update_status_button_color(row, folder_name, has_files)
                
                # 更新未刻版按钮状态（检查订单目录下是否有文件）
                not_engraved_status = status_data.get('not_engraved', {})
                has_files_in_order_dir = not_engraved_status.get('has_files', False)
                self._update_not_engraved_button(row, has_files_in_order_dir)
                
                # 更新固态按钮状态（检查固态目录下是否有文件）
                solid_state_status = status_data.get('solid_state', {})
                has_files_in_solid_dir = solid_state_status.get('has_files', False)
                self._update_solid_state_button(row, has_files_in_solid_dir)
            
            # 其他列（列索引都需要+1）
            self.table.setItem(row, 9, QTableWidgetItem(order_data.get('priority', '')))
            self.table.setItem(row, 10, QTableWidgetItem(order_data.get('notes', '')))
            
            # 是否挂版列 - 下拉框（列索引从10改为11）
            pending_combo = QComboBox()
            pending_combo.addItems(["是", "否"])
            pending_combo.setCurrentText("是" if order_data.get('is_pending_engraving', False) else "否")
            pending_combo.currentTextChanged.connect(lambda text, r=row: self._on_pending_changed(r, text))
            
            # 设置背景色
            is_pending = order_data.get('is_pending_engraving', False)
            if is_pending:
                pending_combo.setStyleSheet("QComboBox { background-color: red; color: white; }")
            else:
                pending_combo.setStyleSheet("QComboBox { background-color: white; color: black; }")
            
            self.table.setCellWidget(row, 11, pending_combo)
            
            # 颜色列 - 下拉框（列索引从11改为12）
            is_pending = order_data.get('is_pending_engraving', False)
            color_combo = QComboBox()
            color_combo.addItems(['', '单黑', '双色', '三色', '四色'])
            if is_pending:
                color = order_data.get('color', '单黑')
                color_combo.setCurrentText(color)
            else:
                color_combo.setCurrentText('')  # 非挂版时显示空白
            color_combo.setEnabled(is_pending)  # 根据挂版状态启用/禁用
            color_combo.currentTextChanged.connect(lambda text, r=row: self._on_color_changed(r, text))
            self.table.setCellWidget(row, 12, color_combo)
            
            # 进纸方向列 - 下拉框（列索引从12改为13）
            direction_combo = QComboBox()
            direction_combo.addItems(['', '上下', '左右'])
            if is_pending:
                paper_direction = order_data.get('paper_direction', '上下')
                direction_combo.setCurrentText(paper_direction)
            else:
                direction_combo.setCurrentText('')  # 非挂版时显示空白
            direction_combo.setEnabled(is_pending)  # 根据挂版状态启用/禁用
            direction_combo.currentTextChanged.connect(lambda text, r=row: self._on_paper_direction_changed(r, text))
            self.table.setCellWidget(row, 13, direction_combo)
            
            # 文件类型列 - 下拉框（列索引从13改为14）
            file_type_combo = QComboBox()
            file_type_combo.addItems(['PDF', 'CDR'])
            file_type = order_data.get('file_type', 'PDF')
            file_type_combo.setCurrentText(file_type)
            file_type_combo.currentTextChanged.connect(lambda text, r=row: self._on_file_type_changed(r, text))
            self.table.setCellWidget(row, 14, file_type_combo)
            
            # 交货日期列 - 日期选择控件
            date_edit = QDateEdit()
            date_edit.setCalendarPopup(True)
            date_edit.setDisplayFormat("yyyy-MM-dd")
            # 设置默认日期为今天
            from PyQt6.QtCore import QDate
            date_edit.setDate(QDate.currentDate())
            # 如果有交货日期数据，设置相应日期
            delivery_date = order_data.get('delivery_date', '')
            if delivery_date and delivery_date != '当天':
                try:
                    # 尝试解析日期字符串
                    if '-' in delivery_date:
                        date_parts = delivery_date.split('-')
                        if len(date_parts) == 3:
                            year, month, day = map(int, date_parts)
                            date_edit.setDate(QDate(year, month, day))
                except:
                    pass
            date_edit.dateChanged.connect(lambda date, r=row: self._on_delivery_date_changed(r, date))
            self.table.setCellWidget(row, 15, date_edit)
            
            # 接单人列 - 下拉框（列索引从15改为16）
            order_taker = order_data.get('order_taker', '1号客服')
            order_taker_combo = QComboBox()
            order_taker_combo.addItems(["1号客服", "2号客服", "3号客服"])
            order_taker_combo.setCurrentText(order_taker)
            order_taker_combo.currentTextChanged.connect(lambda text, r=row: self._on_order_taker_changed(r, text))
            self.table.setCellWidget(row, 16, order_taker_combo)
            
            # 设计人列 - 下拉框（列索引从16改为17）
            designer = order_data.get('designer', '拼版1号')
            designer_combo = QComboBox()
            designer_combo.addItems(["拼版1号", "拼版2号", "外发1号", "外发2号", "外发3号", "外发4号"])
            designer_combo.setCurrentText(designer)
            designer_combo.currentTextChanged.connect(lambda text, r=row: self._on_designer_changed(r, text))
            self.table.setCellWidget(row, 17, designer_combo)
            
            # 校对人列 - 可编辑，变化时自动更新校对时间（列索引从17改为18）
            proofreader_item = QTableWidgetItem(order_data.get('proofreader', ''))
            proofreader_item.setFlags(proofreader_item.flags() | Qt.ItemFlag.ItemIsEditable)  # 设置为可编辑
            self.table.setItem(row, 18, proofreader_item)
            
            # 校对时间列 - 只读，由校对人变化自动更新（列索引从18改为19）
            proofreading_time_item = QTableWidgetItem(order_data.get('proofreading_time', ''))
            proofreading_time_item.setFlags(proofreading_time_item.flags() & ~Qt.ItemFlag.ItemIsEditable)  # 设置为只读
            self.table.setItem(row, 19, proofreading_time_item)
            
            print(f"成功添加新订单: {order_data.get('number', '')} - {order_data.get('customer', '')}")
            
        except Exception as e:
            QMessageBox.critical(self, "添加订单失败", f"添加订单时发生错误: {str(e)}")
        finally:
            # 恢复信号触发
            self.table.blockSignals(False)
            
        # 重新应用当前筛选
        if self.current_filter_status:
            self._apply_status_filter()
            
    def _parse_order_from_path(self, order_path: str):
        """从路径解析订单信息"""
        try:
            folder_name = os.path.basename(order_path)
            parts = folder_name.split("_", 1)
            
            if len(parts) == 2:
                # 创建一个简单的订单信息对象
                class OrderInfo:
                    def __init__(self, path, number, customer):
                        self.path = path
                        self.number = number
                        self.customer = customer
                        self.is_valid = True
                        
                return OrderInfo(order_path, parts[0], parts[1])
                
        except Exception as e:
            print(f"解析订单路径失败 {order_path}: {e}")
            
        return None
        
        
    def _update_row_status_buttons(self, row_index: int, status_folders: List[str]):
        """更新指定行的状态按钮（状态文件夹存在性）"""
        try:
            if row_index < 0 or row_index >= self.table.rowCount():
                return
                
            print(f"更新行 {row_index} 状态文件夹: {status_folders}")
            
            # 注意：按钮颜色现在由 _update_status_button_color 方法根据文件存在性单独处理
            # 这里只是记录状态文件夹的存在性，实际颜色更新在第三级监控中进行
            
        except Exception as e:
            print(f"更新行状态按钮失败: {e}")
            
    def _update_not_engraved_button(self, row_index: int, has_files: bool):
        """更新指定行的未刻版按钮状态（检查订单目录下是否有文件）"""
        try:
            if row_index < 0 or row_index >= self.table.rowCount():
                return
            
            # 阻止信号触发（程序更新样式不触发变更信号）
            should_block = not self.table.signalsBlocked()
            if should_block:
                self.table.blockSignals(True)
                
            # 未刻版按钮在第5列
            widget = self.table.cellWidget(row_index, 5)
            if widget:
                base_style = "border: none; margin: 0px; padding: 0px; border-radius: 0px; min-height: 30px;"
                
                if has_files:
                    # 订单目录下有文件时，未刻版按钮变红色
                    widget.setStyleSheet(f"background-color: #f44336; color: white; {base_style}")
                else:
                    # 订单目录下无文件时，背景透明
                    widget.setStyleSheet(f"background-color: transparent; color: #333; {base_style}")
                
                # 检查并更新完成按钮状态
                self._check_and_update_complete_button(row_index)
            
            # 恢复信号触发
            if should_block:
                self.table.blockSignals(False)
                    
        except Exception as e:
            print(f"更新未刻录按钮失败: {e}")
            # 确保异常时也恢复信号
            if should_block:
                self.table.blockSignals(False)
    
    def _update_solid_state_button(self, row_index: int, has_files: bool):
        """更新指定行的固态按钮状态（检查固态目录下是否有文件）"""
        try:
            if row_index < 0 or row_index >= self.table.rowCount():
                return
            
            # 阻止信号触发（程序更新样式不触发变更信号）
            should_block = not self.table.signalsBlocked()
            if should_block:
                self.table.blockSignals(True)
                
            # 固态按钮在第4列
            widget = self.table.cellWidget(row_index, 4)
            if widget:
                base_style = "border: none; margin: 0px; padding: 0px; border-radius: 0px; min-height: 30px;"
                
                if has_files:
                    # 固态目录下有文件时，固态按钮变红色
                    widget.setStyleSheet(f"background-color: #f44336; color: white; {base_style}")
                else:
                    # 固态目录下无文件时，背景透明
                    widget.setStyleSheet(f"background-color: transparent; color: #333; {base_style}")
                
                # 检查并更新完成按钮状态
                self._check_and_update_complete_button(row_index)
            
            # 恢复信号触发
            if should_block:
                self.table.blockSignals(False)
                    
        except Exception as e:
            print(f"更新固态按钮失败: {e}")
            # 确保异常时也恢复信号
            if should_block:
                self.table.blockSignals(False)
            
    def _check_and_update_complete_button(self, row_index: int):
        """检查固态、未刻版、未确认、挂四个按钮的状态，决定完成按钮是否可用"""
        try:
            if row_index < 0 or row_index >= self.table.rowCount():
                return
            
            # 阻止信号触发（程序更新按钮状态不触发变更信号）
            should_block = not self.table.signalsBlocked()
            if should_block:
                self.table.blockSignals(True)
            
            # 检查固态（第4列）、未刻版（第5列）、未确认（第6列）、挂（第7列）
            buttons_to_check = [4, 5, 6, 7]
            has_red_button = False
            
            for col_index in buttons_to_check:
                status_btn = self.table.cellWidget(row_index, col_index)
                if status_btn:
                    style = status_btn.styleSheet()
                    if "background-color: #f44336" in style:
                        has_red_button = True
                        break
            
            # 根据检查结果启用或禁用完成按钮
            complete_btn = self.table.cellWidget(row_index, 0)
            if complete_btn:
                if has_red_button:
                    # 有红色按钮时，禁用并取消选中完成按钮
                    complete_btn.setEnabled(False)
                    complete_btn.setChecked(False)
                    complete_btn.setText("未完成")
                else:
                    # 没有红色按钮时，启用完成按钮
                    complete_btn.setEnabled(True)
            
            # 恢复信号触发
            if should_block:
                self.table.blockSignals(False)
                    
        except Exception as e:
            print(f"检查和更新完成按钮失败: {e}")
            # 确保异常时也恢复信号
            if should_block:
                self.table.blockSignals(False)
    
    def _update_status_button_color(self, row_index: int, status_folder: str, has_files: bool):
        """更新指定行的状态按钮颜色"""
        try:
            if row_index < 0 or row_index >= self.table.rowCount():
                return
            
            # 阻止信号触发（程序更新样式不触发变更信号）
            should_block = not self.table.signalsBlocked()
            if should_block:
                self.table.blockSignals(True)
                
            # 状态按钮列映射
            status_columns = {
                "固态": 4,      # 固态按钮列
                "未刻版": 5,    # 未刻版按钮列
                "未确认": 6,    # 未确认按钮列
                "挂": 7,        # 挂按钮列
                "已做": 8       # 已做按钮列
            }
            
            if status_folder not in status_columns:
                if should_block:
                    self.table.blockSignals(False)
                return
                
            col = status_columns[status_folder]
            widget = self.table.cellWidget(row_index, col)
            
            if widget:
                base_style = "border: none; margin: 0px; padding: 0px; border-radius: 0px; min-height: 30px;"
                
                if has_files:
                    if status_folder in ["挂", "未确认"]:
                        # 挂和未确认：有文件时变红色
                        widget.setStyleSheet(f"background-color: #f44336; color: white; {base_style}")
                        # 当未确认或挂变红时，需要检查是否禁用完成按钮
                        self._check_and_update_complete_button(row_index)
                    elif status_folder == "已做":
                        # 已做：有文件时变绿色
                        widget.setStyleSheet(f"background-color: #4CAF50; color: white; {base_style}")
                else:
                    # 无文件时：背景透明
                    widget.setStyleSheet(f"background-color: transparent; color: #333; {base_style}")
                    # 按钮变透明时，也需要检查是否可以启用完成按钮
                    if status_folder in ["挂", "未确认"]:
                        self._check_and_update_complete_button(row_index)
            
            # 恢复信号触发
            if should_block:
                self.table.blockSignals(False)
                    
        except Exception as e:
            print(f"更新状态按钮颜色失败: {e}")
            # 确保异常时也恢复信号
            if should_block:
                self.table.blockSignals(False)
            
    def _on_pending_changed(self, row: int, text: str):
        """处理是否挂版下拉框变化"""
        try:
            if row < 0 or row >= len(self.orders_data):
                return
                
            # 更新订单数据
            is_pending = (text == "是")
            self.orders_data[row]['is_pending_engraving'] = is_pending
            
            # 更新下拉框背景色
            pending_combo = self.table.cellWidget(row, 10)
            if pending_combo:
                if is_pending:
                    pending_combo.setStyleSheet("QComboBox { background-color: red; color: white; }")
                else:
                    pending_combo.setStyleSheet("QComboBox { background-color: white; color: black; }")
            
            # 启用/禁用颜色和进纸方向列
            color_combo = self.table.cellWidget(row, 11)
            direction_combo = self.table.cellWidget(row, 12)
            
            if color_combo:
                color_combo.setEnabled(is_pending)
                if not is_pending:
                    color_combo.setCurrentText('')  # 非挂版时显示空白
                else:
                    # 挂版时设置为空
                    color_combo.setCurrentText('')
            if direction_combo:
                direction_combo.setEnabled(is_pending)
                if not is_pending:
                    direction_combo.setCurrentText('')  # 非挂版时显示空白
                else:
                    # 挂版时设置为空
                    direction_combo.setCurrentText('')
            
            # 发送更新到服务端
            if hasattr(self, 'data_changed'):
                # 过滤掉不能存储到数据库的字段
                filtered_data = {k: v for k, v in self.orders_data[row].items() 
                               if k not in ['status_data']}
                self.data_changed.emit(filtered_data)
            
        except Exception as e:
            print(f"处理是否挂版变化失败: {e}")
    
    def _on_delivery_date_changed(self, row: int, date):
        """处理交货日期变化"""
        try:
            if row < 0 or row >= len(self.orders_data):
                return
                
            # 格式化日期
            from PyQt6.QtCore import QDate
            if isinstance(date, QDate):
                date_str = date.toString("yyyy-MM-dd")
            else:
                date_str = str(date)
                
            # 更新订单数据
            self.orders_data[row]['delivery_date'] = date_str
            
            # 发送更新到服务端
            if hasattr(self, 'data_changed'):
                # 过滤掉不能存储到数据库的字段
                filtered_data = {k: v for k, v in self.orders_data[row].items() 
                               if k not in ['status_data']}
                self.data_changed.emit(filtered_data)
            
        except Exception as e:
            print(f"处理交货日期变化失败: {e}")
    
    def _on_color_changed(self, row: int, new_color: str):
        """处理颜色下拉框变化"""
        try:
            if row < 0 or row >= len(self.orders_data):
                return
                
            # 更新订单数据
            self.orders_data[row]['color'] = new_color
            
            # 发送更新到服务端
            if hasattr(self, 'data_changed'):
                # 过滤掉不能存储到数据库的字段
                filtered_data = {k: v for k, v in self.orders_data[row].items() 
                               if k not in ['status_data']}
                self.data_changed.emit(filtered_data)
            
        except Exception as e:
            print(f"处理颜色变化失败: {e}")
    
    def _on_paper_direction_changed(self, row: int, new_direction: str):
        """处理进纸方向下拉框变化"""
        try:
            if row < 0 or row >= len(self.orders_data):
                return
                
            # 更新订单数据
            self.orders_data[row]['paper_direction'] = new_direction
            
            # 发送更新到服务端
            if hasattr(self, 'data_changed'):
                # 过滤掉不能存储到数据库的字段
                filtered_data = {k: v for k, v in self.orders_data[row].items() 
                               if k not in ['status_data']}
                self.data_changed.emit(filtered_data)
                
            
        except Exception as e:
            print(f"处理进纸方向变化失败: {e}")
    
    def _on_file_type_changed(self, row: int, new_file_type: str):
        """处理文件类型下拉框变化"""
        try:
            if row < 0 or row >= len(self.orders_data):
                return
                
            # 更新订单数据
            self.orders_data[row]['file_type'] = new_file_type
            
            # 发送更新到服务端
            if hasattr(self, 'data_changed'):
                # 过滤掉不能存储到数据库的字段
                filtered_data = {k: v for k, v in self.orders_data[row].items() 
                               if k not in ['status_data']}
                self.data_changed.emit(filtered_data)
                
            
        except Exception as e:
            print(f"处理文件类型变化失败: {e}")
    
    def _on_order_taker_changed(self, row: int, new_order_taker: str):
        """处理接单人下拉框变化"""
        try:
            if row < 0 or row >= len(self.orders_data):
                return
                
            # 更新订单数据
            self.orders_data[row]['order_taker'] = new_order_taker
            
            # 发送更新到服务端
            if hasattr(self, 'data_changed'):
                # 过滤掉不能存储到数据库的字段
                filtered_data = {k: v for k, v in self.orders_data[row].items() 
                               if k not in ['status_data']}
                self.data_changed.emit(filtered_data)
            
        except Exception as e:
            print(f"处理接单人变化失败: {e}")
    
    def _on_designer_changed(self, row: int, new_designer: str):
        """处理设计人下拉框变化"""
        try:
            if row < 0 or row >= len(self.orders_data):
                return
                
            # 更新订单数据
            self.orders_data[row]['designer'] = new_designer
            
            # 发送更新到服务端
            if hasattr(self, 'data_changed'):
                # 过滤掉不能存储到数据库的字段
                filtered_data = {k: v for k, v in self.orders_data[row].items() 
                               if k not in ['status_data']}
                self.data_changed.emit(filtered_data)
            
        except Exception as e:
            print(f"处理设计人变化失败: {e}")
    
    def _on_table_item_changed(self, item):
        """处理表格单元格变化"""
        try:
            row = item.row()
            col = item.column()
            
            if row < 0 or row >= len(self.orders_data):
                return
            
            # 客户备注列（第10列）变化时
            if col == 10:  # 客户备注列
                new_notes = item.text()
                
                # 更新订单数据
                self.orders_data[row]['notes'] = new_notes
                
                # 发送更新到服务端
                if hasattr(self, 'data_changed'):
                    # 过滤掉不能存储到数据库的字段
                    filtered_data = {k: v for k, v in self.orders_data[row].items() 
                                   if k not in ['status_data']}
                    self.data_changed.emit(filtered_data)
            
            # 接单人列和设计人列（现在是下拉框，由专门的回调函数处理
            # 不再需要在这里处理
            
            # 校对人列（第18列）变化时，自动更新校对时间
            elif col == 18:  # 校对人列
                new_proofreader = item.text()
                
                # 更新订单数据
                self.orders_data[row]['proofreader'] = new_proofreader
                
                # 如果校对人不为空，自动更新校对时间为当前时间
                if new_proofreader.strip():
                    from datetime import datetime
                    current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                    self.orders_data[row]['proofreading_time'] = current_time
                    
                    # 更新校对时间列显示
                    proofreading_time_item = self.table.item(row, 17)
                    if proofreading_time_item:
                        proofreading_time_item.setText(current_time)
                    
                else:
                    # 如果校对人为空，清空校对时间
                    self.orders_data[row]['proofreading_time'] = ''
                    
                    # 更新校对时间列显示
                    proofreading_time_item = self.table.item(row, 17)
                    if proofreading_time_item:
                        proofreading_time_item.setText('')
                    
                
                # 发送更新到服务端
                if hasattr(self, 'data_changed'):
                    # 过滤掉不能存储到数据库的字段
                    filtered_data = {k: v for k, v in self.orders_data[row].items() 
                                   if k not in ['status_data']}
                    self.data_changed.emit(filtered_data)
            
        except Exception as e:
            print(f"处理表格单元格变化失败: {e}")
    
    def _on_priority_changed(self, row: int, new_priority: str):
        """处理优先级变化"""
        try:
            if row < 0 or row >= len(self.orders_data):
                return
                
            # 更新订单数据
            self.orders_data[row]['priority'] = new_priority
            
            # 发送更新到服务端
            if hasattr(self, 'data_changed'):
                # 过滤掉不能存储到数据库的字段
                filtered_data = {k: v for k, v in self.orders_data[row].items() 
                               if k not in ['status_data']}
                self.data_changed.emit(filtered_data)
            
        except Exception as e:
            print(f"处理优先级变化失败: {e}")

    def __del__(self):
        """析构函数，确保停止数据刷新"""
        self.stop_data_refresh()


